package com.kevin.Code.Array;

/**
 * @author Vinlee Xiao
 * @Classname SearchinRotatedSortedArrayii
 * @Description Leetcode 81. 搜索旋转排序数组 II 中等难度
 * @Date 2021/11/10 16:06
 * @Version 1.0
 */
public class SearchinRotatedSortedArrayii {

    /**
     * @param nums
     * @param target
     * @return
     */
    public boolean search(int[] nums, int target) {

        int index = 0;
        int len = nums.length;

        if (len == 1) {
            if (target == nums[0]) {
                return true;
            } else {
                return false;
            }
        }

        for (int i = 0; i < nums.length; i++) {
            if (nums[i] == target) {
                return true;
            }
            if (i > 0 && nums[i] < nums[i - 1]) {

                index = i;
                break;
            }
        }


        return BinarySearch(nums, index, len - 1, target);
    }


    private boolean BinarySearch(int[] nums, int low, int high, int target) {

        if (high < low) {
            return false;
        }

        int l = low;
        int r = high;

        while (l <= r) {

            int mid = (l + r) / 2;
            if (nums[mid] == target) {
                return true;
            } else if (nums[mid] > target) {
                r = mid - 1;
            } else if (nums[mid] < target) {
                l = mid + 1;
            }

        }

        return false;
    }

    public static void main(String[] args) {
        SearchinRotatedSortedArrayii searchinRotatedSortedArrayii = new SearchinRotatedSortedArrayii();
        int[] nums = new int[]{2, 5, 6, 0, 0, 1, 2};
        boolean b = searchinRotatedSortedArrayii.search(nums, 3);
        System.out.println(b);
    }
}
